package com.lemner.ke.activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lemner.ke.R;
import com.lemner.ke.adapter.DetailAdapter;
import com.lemner.ke.base.BaseListener;
import com.lemner.ke.base.BaseObjectBean;
import com.lemner.ke.base.PlayBaseActivity;
import com.lemner.ke.bean.CommentBean;
import com.lemner.ke.bean.RichEntityBean;
import com.lemner.ke.bean.SuccessBean;
import com.lemner.ke.bean.VideoCloudBean;
import com.lemner.ke.bean.VideoCommentBean;
import com.lemner.ke.bean.VideoPlayBean;
import com.lemner.ke.model.knowledge.PublishVideoCommentModel;
import com.lemner.ke.model.knowledge.VideoCloudIdModel;
import com.lemner.ke.model.knowledge.VideoCollectModel;
import com.lemner.ke.model.knowledge.VideoCommentModel;
import com.lemner.ke.model.knowledge.VideoNiceModel;
import com.lemner.ke.model.knowledge.VideoPlayModel;
import com.lemner.ke.util.LoadImageUtils;
import com.lemner.ke.util.SoftKeyBoardListener;
import com.lemner.ke.util.SpUtils;
import com.lemner.ke.view.video.Clarity;
import com.lemner.ke.view.video.NiceVideoPlayer;
import com.lemner.ke.view.video.NiceVideoPlayerManager;
import com.lemner.ke.view.video.TxVideoPlayerController;

import java.util.ArrayList;
import java.util.List;

import static com.lemner.ke.base.BaseActivity.hideSoftKeyBoard;
import static com.lemner.ke.base.BaseActivity.showSoftKeyBoard;

/**
 * 视频播放
 * @author raintea
 * @date 2018/10/14
 */
public class PlayActivity extends PlayBaseActivity implements CompoundButton.OnCheckedChangeListener{

    RecyclerView rvRec;
    DetailAdapter listAdapter;
    int pageNumber=0;
    boolean publishs=true;
    String commentIds;

    //底部评论
    TextView commentNum;
    CheckBox playCollect;
    CheckBox playNice;
    TextView commentInput;
    LinearLayout llPlayComment;
    RelativeLayout rlPlayCommentShow;
    TextView btnSendPlayComment;
    TextView tvSendPlayComment;

    //登陆状态
    int loginStatus;
    String userIds;
    //视频播放
    private String title = "";
    private TxVideoPlayerController controller;
    private NiceVideoPlayer nvp_play;
    private TextView tv_aty_play;
    private LinearLayout ll_back;
    @Override
    public int getLayoutFile() {
        return R.layout.activity_play;
    }

    @Override
    public void initView() {
        rvRec=findViewById(R.id.rv_comment);

        nvp_play=findViewById(R.id.nvp_play);
        tv_aty_play = findViewById(R.id.tv_aty_play);
        ll_back = findViewById(R.id.ll_back);//返回
        //下方评论
        commentNum=findViewById(R.id.tv_play_comment_num);
        playCollect=findViewById(R.id.cb_play_collect);
        playNice=findViewById(R.id.cb_play_nice);
        commentInput=findViewById(R.id.et_play_comment_input);
        llPlayComment=findViewById(R.id.ll_play_comment);
        rlPlayCommentShow=findViewById(R.id.rl_play_comment_show);
        btnSendPlayComment=findViewById(R.id.btn_play_send_comment);
        tvSendPlayComment=findViewById(R.id.tv_play_send_comment);

    }

    @Override
    public void initEvent() {
        playNice.setOnCheckedChangeListener(this);
        playCollect.setOnCheckedChangeListener(this);
        btnSendPlayComment.setOnClickListener(this);
        tvSendPlayComment.setOnClickListener(this);
        commentNum.setOnClickListener(this);

        ll_back.setOnClickListener(this);

        LinearLayoutManager layoutManager=new LinearLayoutManager(this);
        listAdapter = new DetailAdapter(R.layout.item_play_rv);

        rvRec.setLayoutManager(layoutManager);
        listAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
//                rvAComment.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        getComment();
//                    }
//                }, 2);
                getComment();
            }

        }, rvRec);
        rvRec.setAdapter(listAdapter);


        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                //点此评论
                llPlayComment.setVisibility(View.GONE);
                //点此评论弹出的输入框
                rlPlayCommentShow.setVisibility(View.VISIBLE);
                commentInput.requestFocus();
            }

            @Override
            public void keyBoardHide(int height) {
                llPlayComment.setVisibility(View.VISIBLE);
                rlPlayCommentShow.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        commentIds = intent.getStringExtra("ids");
        userIds = SpUtils.getString(this, SpUtils.USERIDS);

        nvp_play.setPlayerType(NiceVideoPlayer.TYPE_IJK);//设置播放器类型
        controller = new TxVideoPlayerController(this);
        controller.setTitle(title);
        controller.setNormalLl(ll_back);
        getComment();
        getPlayCloud();

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_play_send_comment:
                if (loginStatus == SpUtils.LOGIN) {
                    showSoftKeyBoard(this);
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.btn_play_send_comment:
                String inputStr = commentInput.getText().toString();
                if (!inputStr.isEmpty()) {
                    // 发送评论
                    publishComment(inputStr);
                    hideSoftKeyBoard(this);
                } else {
                    hideSoftKeyBoard(this);
                }
                break;
            case R.id.tv_play_comment_num:
                rvRec.scrollToPosition(1);
                break;
            case R.id.ll_back:
                finish();
                break;
            default:
        }
    }

    public void getComment() {
        pageNumber++;
        // 获取评论数据
        new VideoCommentModel().getVideoComment(new BaseListener<VideoCommentBean>() {
            @Override
            public void onResponse(VideoCommentBean videoCommentBean) {
                if (videoCommentBean != null) {
                    VideoCommentBean.DataBean dataBean = videoCommentBean.getData();
                    if (dataBean != null) {
                        List<VideoCommentBean.DataBean.ListBean> datas = dataBean.getList();
//                                hasNextPage = videoCommentBean.getData().isHasNextPage();
                        if (publishs){
                            listAdapter.addData(datas);
                        }
                        if (datas.size() < 20) {
                            listAdapter.loadMoreEnd();
                        }
                        if (datas.size()==20){
                            listAdapter.loadMoreComplete();
                        }
                        publishs=true;
                    }
                }
            }

            @Override
            public void onFail(String msg) {

            }
        }, commentIds, pageNumber);
    }

    @Override
    public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
        if (loginStatus == SpUtils.LOGIN) {
            userIds = SpUtils.getString(this, SpUtils.USERIDS);
            switch (buttonView.getId()) {
                case R.id.cb_play_nice:
                    if (isChecked) {
                        // 点赞
                        new VideoNiceModel().niceVideo(commentIds, userIds, new BaseListener<SuccessBean>() {
                            @Override
                            public void onResponse(SuccessBean successBean) {
                                if (successBean.getCode().equals("1000")) {
                                    String contentStr = (String) buttonView.getText();
                                    int num = Integer.valueOf(contentStr);
                                    buttonView.setText(++num + "");
                                    Toast.makeText(PlayActivity.this, successBean.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFail(String msg) {

                            }
                        });

                    } else {
                        // 取消点赞
                        new VideoNiceModel().unNiceVideo(commentIds, userIds, new BaseListener<SuccessBean>() {
                            @Override
                            public void onResponse(SuccessBean successBean) {
                                if (successBean.getCode().equals("1000")) {
                                    String contentStr = (String) buttonView.getText();
                                    int num = Integer.valueOf(contentStr);
                                    buttonView.setText(--num + "");
                                    Toast.makeText(PlayActivity.this, successBean.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFail(String msg) {

                            }
                        });

                    }
                    break;
                case R.id.cb_play_collect:
                    if (isChecked) {
                        // 收藏
                        new VideoCollectModel().collectVideo(commentIds, userIds, new BaseListener<SuccessBean>() {
                            @Override
                            public void onResponse(SuccessBean successBean) {
                                if (successBean.getCode().equals("1000")) {
                                    String contentStr = (String) buttonView.getText();
                                    int num = Integer.valueOf(contentStr);
                                    buttonView.setText(++num + "");
                                    Toast.makeText(PlayActivity.this, successBean.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFail(String msg) {

                            }
                        });
                    } else {
                        String contentStr = (String) buttonView.getText();
                        int num = Integer.valueOf(contentStr);
                        Log.d("xxxx", num + "--------");
                        if (num != 0) {
                            // 取消收藏
                            new VideoCollectModel().unCollectVideo(commentIds, userIds, new BaseListener<SuccessBean>() {
                                @Override
                                public void onResponse(SuccessBean successBean) {
                                    Log.d("xxxx", successBean.getCode());
                                    if (successBean.getCode().equals("1000")) {
                                        String contentStr = (String) buttonView.getText();
                                        int num = Integer.valueOf(contentStr);
                                        buttonView.setText(--num + "");
                                        Toast.makeText(PlayActivity.this, successBean.getMsg(), Toast.LENGTH_SHORT).show();
                                    }
                                }

                                @Override
                                public void onFail(String msg) {

                                }
                            });
                        }
                    }
                    break;
                    default:
            }
        } else {
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loginStatus = SpUtils.getInt(PlayActivity.this, SpUtils.LOGIN_STATUS);
    }



    private void publishComment(String inputStr) {

        pageNumber=0;
        publishs=false;
        userIds = SpUtils.getString(this, SpUtils.USERIDS);
        new PublishVideoCommentModel().publishComment(commentIds, inputStr, userIds, "comment", new BaseListener<BaseObjectBean<CommentBean>>() {
            @Override
            public void onResponse(BaseObjectBean<CommentBean> successBean) {
                if (successBean.getCode().equals("1000")) {
                    hideSoftKeyBoard(PlayActivity.this);
                    commentInput.setText("");
                    // 获取评论数据
                    new VideoCommentModel().getVideoComment(new BaseListener<VideoCommentBean>() {
                        @Override
                        public void onResponse(VideoCommentBean videoCommentBean) {
                            if (videoCommentBean != null) {
                                VideoCommentBean.DataBean dataBean = videoCommentBean.getData();
                                if (dataBean != null) {
                                    List<VideoCommentBean.DataBean.ListBean> datas = dataBean.getList();
//                                    adapter.insertData(datas.get(0));
//                                    adapter.addData(0,datas.get(0));
                                    listAdapter.setNewData(datas);
                                    rvRec.scrollToPosition(1);
                                    String cmStr = commentNum.getText().toString();
                                    if (cmStr != null) {
                                        int cmCount = Integer.valueOf(cmStr);
                                        commentNum.setText(++cmCount + "");
                                    }
                                }
                            }
                        }

                        @Override
                        public void onFail(String msg) {

                        }
                    }, commentIds, 1);
                }
            }

            @Override
            public void onFail(String msg) {

            }
        });
    }

    //获取视频
    public void getPlayCloud(){
        // 获取视频
        new VideoCloudIdModel().getVideoCloudId(new BaseListener<BaseObjectBean<VideoCloudBean>>() {
            @Override
            public void onResponse(BaseObjectBean<VideoCloudBean> videoCloudBeanBaseObjectBean) {
                if (videoCloudBeanBaseObjectBean != null) {
                    VideoCloudBean cloudBean = videoCloudBeanBaseObjectBean.getData();
                    if (cloudBean != null) {
                        String cloudId = cloudBean.getCloudid();
                        // 获取点赞数，评论数，收藏数
                        String collectnum = cloudBean.getCollectnnum();
                        playCollect.setText(collectnum);
                        String commentnum = cloudBean.getCommentnum();
                        commentNum.setText(commentnum);
                        String likenum = cloudBean.getLikesnum();
                        playNice.setText(likenum);

                        Object isLike = cloudBean.getIslikes();
                        if (isLike != null) {
//                            boolean isLikeBool = (boolean) isLike;
//                            cb_nice.setChecked(isLikeBool);
                            if (isLike.equals("likes")) {
                                playNice.setChecked(true);
                            } else {
                                playNice.setChecked(false);
                            }
                        }
                        Object isCollect = cloudBean.getIscollect();
                        if (isCollect != null) {
//                            boolean isCollectBool = (boolean) isCollect;
//                            cb_collect.setChecked(isCollectBool);
                            if (isCollect.equals("collect")) {
                                playCollect.setChecked(true);
                            } else {
                                playCollect.setChecked(false);
                            }
                        }


                        new VideoPlayModel().getVideoUrl(new BaseListener<VideoPlayBean>() {
                            @Override
                            public void onResponse(VideoPlayBean videoPlayBean) {

                                if (videoPlayBean != null) {
                                    if (null != videoPlayBean.getVideoBase().getCoverURL()) {
                                        LoadImageUtils.loadImage(videoPlayBean.getVideoBase().getCoverURL(), controller.imageView());
                                    }
                                    controller.setClarity(getClarities(videoPlayBean), 1);
                                    nvp_play.setController(controller);
                                }



                            }

                            @Override
                            public void onFail(String msg) {

                            }
                        }, cloudId);
                    }
                }
            }

            @Override
            public void onFail(String msg) {

            }
        }, commentIds, userIds);
    }

    private List<Clarity> getClarities(VideoPlayBean videoPlayBean) {
        List<Clarity> list = new ArrayList<>();
        List<VideoPlayBean.PlayInfoListBean.PlayInfoBean> infoList = videoPlayBean.getPlayInfoList().getPlayInfo();
        if (infoList != null && infoList.size() > 0) {
            for (VideoPlayBean.PlayInfoListBean.PlayInfoBean info : infoList) {
                String grade = "";
                String p = "";
                if (info.getDefinition().equals("FD")) {
                    grade = "流畅";
                    p = "270P";
                } else if (info.getDefinition().equals("LD")) {
                    grade = "标清";
                    p = "480P";
                } else if (info.getDefinition().equals("SD")) {
                    grade = "超清";
                    p = "720P";
                } else if (info.getDefinition().equals("OD")) {
                    grade = "原画";
                    p = "1080P";
                }

                Clarity c = new Clarity(grade, p, info.getPlayURL());
                list.add(c);
            }
        }

//        list.add(new Clarity("标清","270P","http://47.94.224.139:8080/uploadFile/video.mp4"));
//        list.add(new Clarity("高清","480P","http://47.94.224.139:8080/uploadFile/video.mp4"));
//        list.add(new Clarity("超清","720P","http://47.94.224.139:8080/uploadFile/video.mp4"));
//        list.add(new Clarity("蓝光","1280P","http://47.94.224.139:8080/uploadFile/video.mp4"));
        return list;
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 在onStop时释放掉播放器
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
    }

    @Override
    public void onBackPressed() {
        // 在全屏或者小窗口时按返回键要先退出全屏或小窗口，
        // 所以在Activity中onBackPress要交给NiceVideoPlayer先处理。
        if (NiceVideoPlayerManager.instance().onBackPressd()) return;
        super.onBackPressed();
    }
}
